<template>
  <div>
    <div class="container">
      <h2>收费套餐统计</h2>
      <el-divider></el-divider>

      <!-- 表格部分 -->
      <el-table :data="pagedData" stripe style="width: 100%">
        <el-table-column prop="packageId" label="编号" width="120" />
        <el-table-column prop="name" label="套餐名称" />
        <el-table-column prop="courseType" label="类型" />
        <el-table-column prop="totalClasses" label="课时数" />
        <el-table-column prop="price" label="价格（元）" />
        <el-table-column prop="discount" label="折扣" />
        <el-table-column prop="validDays" label="有效期（天）" />
      </el-table>

      <!-- 分页 -->
      <el-pagination
        class="pagination"
        background
        layout="prev, pager, next"
        :page-size="pageSize"
        :total="data.length"
        @current-change="handlePageChange"
      />

      <!-- 图表 -->
      <div ref="chartDom" class="chart" />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'

// 所有数据
const data = ref([])
// 当前页码数据
const pagedData = ref([])

// 分页参数
const pageSize = 7
const currentPage = ref(1)

// 表格分页逻辑
const handlePageChange = (page) => {
  currentPage.value = page
  const start = (page - 1) * pageSize
  const end = start + pageSize
  pagedData.value = data.value.slice(start, end)
}

// 图表
const chartDom = ref(null)
let chartInstance = null

const renderChart = () => {
  if (!chartInstance && chartDom.value) {
    chartInstance = echarts.init(chartDom.value)
  }

  const option = {
    title: { text: '套餐价格与课时数' },
    tooltip: {},
    legend: { data: ['价格', '课时数'] },
    xAxis: {
      type: 'category',
      data: data.value.map(item => item.name),
    },
    yAxis: { type: 'value' },
    series: [
      {
        name: '价格',
        type: 'bar',
        data: data.value.map(item => item.price),
      },
      {
        name: '课时数',
        type: 'line',
        data: data.value.map(item => item.totalClasses),
      },
    ],
  }

  chartInstance.setOption(option)
}

onMounted(async () => {
  const res = await axios.get('http://localhost:8080/api/packages')
  data.value = res.data
  handlePageChange(1)
  await nextTick()
  renderChart()
})

window.addEventListener('resize', () => {
  chartInstance && chartInstance.resize()
})
</script>

<style scoped>
.container {
  padding: 20px;
  background-color: #fff;
}

.chart {
  width: 100%;
  height: 400px;
  margin-top: 40px;
}

.pagination {
  margin: 20px 0;
  text-align: center;
}
</style>
